package com.hopu.blb_erp.controller;

import com.hopu.blb_erp.entity.PageEntity;
import com.hopu.blb_erp.entity.Role;
import com.hopu.blb_erp.service.RoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api
@RestController
public class RoleController {

    @Autowired
    private RoleService roleService;

    @ApiOperation("根据用户名查询用户的所有角色")
    @GetMapping("/roleByName/{username}")
    public ResponseEntity<List<Role>> findRoleByName(@PathVariable("username") String username){
        List<Role> roles = roleService.findByName(username);
        return ResponseEntity.ok(roles);
    }

    @ApiOperation("查询所有角色")
    @GetMapping("/roles")
    public ResponseEntity<List<Role>> findAll(){
        List<Role> roles = roleService.findAll();
        return ResponseEntity.ok(roles);
    }

    @ApiOperation("分页查询角色")
    @GetMapping("/roles/{current}/{pageSize}")
    public ResponseEntity<PageEntity> findPage(@PathVariable("current")Integer current, @PathVariable("pageSize")Integer pageSize){
        // 查询角色总数
        Integer count = roleService.findCount();
        // 分页查询订单
        List<Role> roles = roleService.findPage((current-1) * pageSize, pageSize);
        // 包装到分页对象
        PageEntity<Role> page = new PageEntity<>();
        page.setCount(count);
        page.setData(roles);
        return ResponseEntity.ok(page);
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @ApiOperation("添加角色")
    @PostMapping("/role")
    public ResponseEntity<String> add(@RequestBody Role role){
        roleService.add(role);
        return ResponseEntity.ok("ok");
    }

    /**
     * 更新角色
     * @param role
     * @return
     */
    @ApiOperation("根据id更新角色")
    @PutMapping("/role")
    public ResponseEntity<String> modify(@RequestBody Role role){
        roleService.modifyById(role);
        return ResponseEntity.ok("ok");
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @ApiOperation("根据id删除角色")
    @DeleteMapping("/role/{id}")
    public ResponseEntity<String> remove(@PathVariable("id")String id){
        roleService.removeById(id);
        return ResponseEntity.ok("ok");
    }

    /**
     * 根据id查询角色
     * @param id
     * @return
     */
    @ApiOperation("根据id查询角色")
    @GetMapping("/role/{id}")
    public ResponseEntity<Role> find(@PathVariable("id") String id){
        Role role = roleService.findById(id);
        return ResponseEntity.ok(role);
    }
}
